package com.caochenlei.codebuilder.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ReflectUtil {

    /**
     * 功能说明：获取某个类的所有私有方法名称
     *
     * @param clazz
     * @return
     */
    public static List<String> parse(Class<? extends Object> clazz) {
        List<String> list = new ArrayList<String>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            list.add(field.getName());
        }
        return list;
    }

    /**
     * 功能说明：获取某个类的所有私有方法名称，并排除指定名称
     *
     * @param clazz
     * @param excludeNames
     * @return
     */
    public static List<String> parse(Class<? extends Object> clazz, String[] excludeNames) {
        List<String> list = new ArrayList<String>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            list.add(field.getName());
        }
        return list.stream().distinct().filter(name -> {
            for (String excludeName : excludeNames) {
                if (excludeName.equals(name)) return false;
            }
            return true;
        }).collect(Collectors.toList());
    }

    /**
     * 功能说明：根据成员变量获取值
     *
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getValueFormObject(Object object, String fieldName) {
        if (object == null) {
            return null;
        }
        if (fieldName == null || fieldName.length() == 0) {
            return null;
        }

        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            if (field != null) {
                field.setAccessible(true);
                return field.get(object);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 功能说明：通过参数列表和入参对象替换指定字符串的内容
     *
     * @param oldContent
     * @param params
     * @param object
     * @return
     */
    public static String assignment(String oldContent, List<String> params, Object object) {
        for (String param : params) {
            Object valueFormObject = getValueFormObject(object, param);
            if (valueFormObject != null) {
                oldContent = oldContent.replace("[" + param + "]", (String) valueFormObject);
            }
        }
        return oldContent;
    }

}
